<template>
  <div class="page-container">
    <div class="common-content-wrap">
      <TrTable
        ref="trTable"
        isNeedSelection
        :btnList="btnList"
        :total="totalNum"
        v-model="searchParams"
        :searchShowList="searchShowList"
        :tableColumn="tableColumn"
        requestName="searchHandle"
        :tableData="assTableData"
        @add="operateHandle($event, 'add')"
        @rowEdit="operateHandle($event, 'rowEdit')"
        @remove="operateHandle($event, 'remove')"
        @rowDetail="operateHandle($event, 'rowDetail')"
        @rowAssociation="operateHandle($event, 'rowAssociation')"
      />
      <TrEditPopup
        v-model="isShowEdit"
        :width="480"
        :title="checkTitle"
        :labelWidth="114"
        :valueObj.sync="formObj"
        :formData="formData"
        :list="popupList"
        @close="isShowEdit = false"
        @confrim="confrimHandle"
      />

      <TrLayout
        v-model="isShowDetailPopup"
        :title="checkDetailTitle"
        :isNeedFooter="false"
        :width="1227"
        @close="closeDetailPopupHandle"
      >
        <!-- 明细 -->
        <TrTable
          v-if="currentDetailType === 'detail'"
          lazy
          isNeedSelection
          isPopup
          slotStart
          ref="detailTable"
          :btnList="btnDetailList"
          :tableColumn="tableDetailColumn"
          :tableData="detailTableData"
          :isNeedPagination="false"
          :loadFun="loadFun"
          @add="operateDetailHandle($event, 'add')"
          @rowEdit="operateDetailHandle($event, 'rowEdit')"
          @rowRemove="operateDetailHandle($event, 'rowRemove')"
        />

        <TrEditPopup
          v-if="currentDetailType === 'detail'"
          v-model="isShowDetailEdit"
          :title="checkTitle"
          :width="480"
          :valueObj.sync="detailFormObj"
          :formData="detailFormData"
          :list="popupDetailList"
          @close="isShowDetailEdit = false"
          @confrim="detailPopupConfirmHandle"
        />
        <!-- 关联 -->
        <TrTable
          v-if="currentDetailType === 'association'"
          lazy
          isNeedSelection
          isPopup
          slotStart
          ref="associationTable"
          :loadFun="loadFun"
          :btnList="btnAssociationList"
          :tableColumn="tableAssociationColumn"
          :tableData="associationTableData"
          :isNeedPagination="false"
          @add="operateAssociationHandle($event, 'add')"
          @remove="operateAssociationHandle($event, 'remove')"
          @rowRemove="operateAssociationHandle($event, 'rowRemove')"
        />

        <TrEditPopup
          v-if="currentDetailType === 'association'"
          v-model="isShowAssociationEdit"
          :title="checkTitle"
          :width="480"
          :labelWidth="114"
          :valueObj.sync="associationFormObj"
          :formData="associationFormData"
          :relationList="relationList"
          :list="popupAssociationList"
          @close="isShowAssociationEdit = false"
          @confrim="associationConfirmHandle"
        />
      </TrLayout>
    </div>
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  remove,
  add,
  edit,
  getDetailList,
  detailAdd,
  detailEdit,
  detailRemove,
  getAssociationList,
  associationAdd,
  associationRemove,
} from "@/api/baseCode/packingSpecification";
import enumData from "@/utils/enumCode.js";
import TrTable from "@/components/Tr-table/Tr-table.vue";
import TrLayout from "@/components/Tr-layout/Tr-layout.vue";
import TrEditPopup from "@/components/Tr-edit/Tr-edit-popup.vue";

export default {
  components: {
    TrTable,
    TrLayout,
    TrEditPopup,
  },
  name: "packingSpecification",
  data: () => ({
    tableColumn: [
      {
        type: "text",
        label: "包装规则代码",
        value: "packageSpecCode",
      },
      {
        type: "text",
        label: "包装规则名称",
        value: "packageSpecName",
      },
      {
        type: "text",
        label: "创建人员",
        value: "createUserName",
      },
      {
        type: "text",
        label: "创建时间",
        value: "createTime",
      },
      {
        type: "text",
        label: "修改人员",
        value: "updateUserName",
      },
      {
        type: "text",
        label: "修改时间",
        value: "updateTime",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 140,
        showBtnList: [
          {
            label: "编辑",
            option: "rowEdit",
          },
          {
            label: "明细",
            option: "rowDetail",
          },
          {
            label: "关联",
            option: "rowAssociation",
          },
        ],
      },
    ],
    searchShowList: [
      {
        id: "packageSpecCode",
        type: "input",
        width: 33.33,
        label: "包装规则代码",
        value: "",
      },
      {
        id: "categoryName",
        type: "input",
        width: 33.33,
        label: "物料类型",
        value: "",
      },
      {
        id: "materialName",
        type: "input",
        width: 33.33,
        label: "物料",
        value: "",
      },
    ],
    btnList: [
      {
        label: "新增",
        option: "add",
        color: "blue",
      },
      {
        label: "删除",
        option: "remove",
        color: "white",
        isRelaTable: true,
      },
    ],
    popupList: [
      {
        label: "包装规则代码",
        type: "input",
        width: 100,
        value: "",
        id: "packageSpecCode",
      },
      {
        label: "包装规则名称",
        type: "input",
        width: 100,
        value: "",
        id: "packageSpecName",
      },
    ],
    assTableData: [],
    assetsTypeEnum: [],
    formObj: {},
    formData: {},
    searchParams: {
      current: 1,
      size: 10,
    },
    totalNum: 0,
    currentHandle: "add",
    isShowEdit: false,
    // 明细
    isShowDetailPopup: false,
    currentDetailType: "detail",
    isShowDetailEdit: false,
    tableDetailColumn: [
      {
        type: "text",
        label: "包装类型",
        value: "packageTypeName",
      },
      {
        type: "text",
        label: "数量",
        value: "num",
      },
      {
        type: "text",
        label: "单位",
        value: "newNumUnit",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 120,
        showBtnList: [
          {
            label: "编辑",
            option: "rowEdit",
          },
          {
            label: "删除",
            option: "rowRemove",
          },
        ],
      },
    ],
    detailTableData: [],
    btnDetailList: [
      {
        label: "新增",
        option: "add",
        color: "blue",
      },
    ],
    popupDetailList: [
      {
        label: "包装类型",
        type: "select",
        width: 100,
        value: "",
        List: [],
        id: "packageType",
      },
      {
        label: "数量",
        type: "input",
        width: 100,
        inputType: "number",
        value: "",
        id: "num",
      },
      {
        label: "单位",
        type: "loadselect",
        width: 100,
        value: "",
        selectedLabel: "",
        reviewLabel: "unitCode",
        requestObj: {
          url: "/api/trio-system/unit/page",
          method: "post",
          searchKey: "unitName",
          rlLabel: "unitCode(unitName)",
          rlValue: "u9Code",
          resultKey: "data,data,records",
        },
        id: "unitCode",
      },
      {
        label: "父级类型",
        type: "loadselect",
        width: 100,
        value: "",
        list: [],
        selectedLabel: "",
        reviewLabel: "",
        requestObj: {
          url: "/api/mes-production-service/package-spec-detail/page",
          method: "post",
          searchKey: "packageTypeName",
          rlLabel: "packageTypeName",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {
          packageSpecId: "",
        },

        id: "parentId",
        isNeed: false,
      },
    ],
    detailFormObj: { packageSpecId: null, parentId: 0 },
    detailFormData: {},
    // 关联
    isShowAssociationEdit: false,
    tableAssociationColumn: [
      {
        type: "text",
        label: "物料类型编码",
        value: "categoryCode",
      },
      {
        type: "text",
        label: "物料类型名称",
        value: "categoryName",
      },
      {
        type: "text",
        label: "物料编码",
        value: "materialCode",
      },
      {
        type: "text",
        label: "物料名称",
        value: "materialName",
      },
      {
        type: "option",
        label: "操作",
        fixed: "right",
        width: 80,
        showBtnList: [
          {
            label: "删除",
            option: "rowRemove",
          },
        ],
      },
    ],
    associationTableData: [],
    btnAssociationList: [
      {
        label: "新增",
        option: "add",
        color: "blue",
      },
      {
        label: "删除",
        option: "remove",
        color: "white",
        isRelaTable: true,
      },
    ],
    popupAssociationList: [
      {
        label: "物料类型编码",
        type: "loadselect",
        width: 100,
        value: "",
        list: [],
        selectedLabel: "",
        reviewLabel: "",
        requestObj: {
          url: "/api/mes-production-service/material-category/page",
          method: "post",
          searchKey: "categoryCode",
          rlLabel: "categoryCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {},
        id: "materialCategoryId",
      },
      {
        label: "物料类别名称",
        type: "input",
        width: 100,
        disabled: true,
        value: "",
        id: "materialCategoryName",
      },
      {
        label: "物料料号",
        type: "loadselect",
        width: 100,
        value: "",
        list: [],
        selectedLabel: "",
        reviewLabel: "",
        isNeed: false,
        requestObj: {
          url: "/api/mes-production-service/material/page",
          method: "post",
          searchKey: "materialCode",
          rlLabel: "materialCode",
          rlValue: "id",
          resultKey: "data,data,records",
        },
        defaultParams: {},
        id: "materialId",
      },
      {
        label: "物料名称",
        type: "input",
        width: 100,
        disabled: true,
        value: "",
        id: "materialName",
        isNeed: false,
      },
    ],
    relationList: [
      {
        id: "materialCategoryId",
        relaList: [
          {
            relaId: "materialCategoryName",
            relaValue: "categoryName",
            reviewValue: "categoryName",
            disabled: true,
          },
          {
            relaId: "materialId",
            isNotStrict: true,
            params: [
              {
                labelWord: "materialCategoryId",
                realWord: "rlValue",
              },
            ],
          },
        ],
      },
      {
        id: "materialId",
        relaList: [
          {
            relaId: "materialName",
            relaValue: "materialName",
            reviewValue: "materialName",
            disabled: true,
          },
          {
            relaId: "materialCategoryId",
            isNotStrict: true,
            params: [
              {
                labelWord: "categoryCode",
                realWord: "materialCategoryCode",
              },
            ],
          },
        ],
      },
    ],
    associationFormObj: { packageSpecId: null },
    associationFormData: {},
  }),
  methods: {
    async operateHandle(val, type) {
      this.currentHandle = type;
      this.$validateData(val, 3);
      this.formData = type == "add" ? {} : val;
      let parentIdItem = this.$findByProperty(
        this.popupDetailList,
        "id",
        "parentId"
      );
      switch (type) {
        case "add":
          this.$findByProperty(
            this.popupList,
            "id",
            "packageSpecCode"
          ).disabled = false;
          this.isShowEdit = true;
          console.log("新增！！");
          break;
        case "remove":
          this.remove();
          console.log("删除！！");
          break;
        case "rowEdit":
          this.$findByProperty(
            this.popupList,
            "id",
            "packageSpecCode"
          ).disabled = true;
          this.isShowEdit = true;
          console.log("编辑！！");
          break;
        case "rowDetail":
          await this.getDetailList(val.id);
          this.isShowDetailPopup = true;
          this.detailFormObj.packageSpecId = val.id;
          parentIdItem.defaultParams.packageSpecId = val.id;
          console.log("查看明细！！");
          break;
        case "rowAssociation":
          await this.getAssociationList(val.id);
          this.isShowDetailPopup = true;
          this.associationFormObj.packageSpecId = val.id;
          console.log("查看关联！！");
          break;
      }
    },
    operateDetailHandle(val, type) {
      this.$validateData(val, 3);
      this.currentHandle = type;
      this.detailFormData = type == "add" ? {} : val;
      switch (type) {
        case "add":
          this.isShowDetailEdit = true;
          this.$findByProperty(
            this.popupDetailList,
            "id",
            "packageType"
          ).disabled = false;
          this.$findByProperty(
            this.popupDetailList,
            "id",
            "parentId"
          ).disabled = false;
          console.log("明细新增！！");
          break;
        case "rowRemove":
          this.detailRemove(val.id);
          console.log("删除！！");
          break;
        case "rowEdit":
          this.$findByProperty(
            this.popupDetailList,
            "id",
            "packageType"
          ).disabled = true;
          this.$findByProperty(
            this.popupDetailList,
            "id",
            "parentId"
          ).disabled = true;
          this.isShowDetailEdit = true;
          console.log("明细编辑！！");
          break;
      }
    },
    operateAssociationHandle(val, type) {
      this.$validateData(val, 3);
      this.currentHandle = type;
      this.associationFormData = type == "add" ? {} : val;
      switch (type) {
        case "add":
          this.isShowAssociationEdit = true;
          console.log("关联新增！！");
          break;
        case "remove":
          this.associationRemove(this.associationIds);
          console.log("批量删除！！");
          break;
        case "rowRemove":
          this.associationRemove([val.id]);
          console.log("删除！！");
          break;
      }
    },
    closeDetailPopup() {
      this.isShowDetailPopup = false;
    },
    confrimHandle() {
      if (this.currentHandle == "rowEdit") {
        this.formObj.id = this.formData.id;
        this.edit(this.formObj);
      } else if (this.currentHandle == "add") {
        this.add(this.formObj);
      }
      this.isShowEdit = false;
    },
    detailPopupConfirmHandle() {
      if (this.currentHandle == "rowEdit") {
        this.detailFormObj.id = this.detailFormData.id;
        this.detailEdit(this.detailFormObj);
      } else if (this.currentHandle == "add") {
        this.detailAdd(this.detailFormObj);
      }
      this.isShowDetailEdit = false;
    },
    associationConfirmHandle() {
      console.log(this.associationFormObj, this.associationFormData);
      if (this.currentHandle == "rowEdit") {
        this.associationFormObj.id = this.associationFormData.id;
        this.detailEdit(this.associationFormObj);
      } else if (this.currentHandle == "add") {
        this.associationAdd(this.associationFormObj);
      }
    },
    closeDetailPopupHandle() {
      this.isShowDetailPopup = false;
    },
    searchHandle() {
      this.getList();
    },
    remove() {
      this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t("tip.delete")],
      })
        .then(async () => {
          let res = await remove({ ids: this.ids });
          if (res.data.code != 200) return;
          this.$message.success(this.$t("msg.success"));
          this.$refs.trTable.clearSelect();
          this.getList();
        })
        .catch(() => {});
    },
    add(params) {
      add(params).then((res) => {
        if (res.data.code != 200) return;
        this.$message.success(this.$t("msg.success"));
        this.isShowEdit = false;
        this.getList();
      });
    },
    async edit(params) {
      let res = await edit(params);
      if (res.data.code != 200) return;
      this.$message.success(this.$t("msg.success"));
      this.$refs.trTable.clearSelect();
      this.getList();
    },
    detailAdd(params) {
      detailAdd(params).then((res) => {
        if (res.data.code != 200) return;
        this.$message.success(this.$t("msg.success"));
        this.getDetailList(this.detailFormObj.packageSpecId);
        this.isShowDetailEdit = false;
      });
    },
    associationAdd(params) {
      associationAdd(params).then((res) => {
        if (res.data.code != 200) return;
        this.$message.success(this.$t("msg.success"));
        this.isShowAssociationEdit = false;
        this.getAssociationList(this.associationFormObj.packageSpecId);
      });
    },
    async detailEdit(params) {
      let res = await detailEdit(params);
      if (res.data.code != 200) return;
      this.detailTableData = [];
      this.$message.success(this.$t("msg.success"));
      this.$refs.trTable.clearSelect();
      this.getDetailList(this.detailFormObj.packageSpecId);
    },
    detailRemove(id) {
      this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t("tip.delete")],
      })
        .then(async () => {
          let res = await detailRemove({ ids: [id] });
          if (res.data.code != 200) return;
          this.$message.success(this.$t("msg.success"));
          this.$refs.detailTable.clearSelect();
          this.getDetailList(this.detailFormObj.packageSpecId);
        })
        .catch(() => {});
    },
    async associationRemove(ids) {
      await this.$textShow({
        title: this.$t("tip.label"),
        content: [this.$t("tip.delete")],
      });

      let { data } = await associationRemove({ ids });
      if (data.code != 200) return;
      this.$message.success(this.$t("msg.success"));
      this.$refs.associationTable.clearSelect();
      await this.getAssociationList(this.associationFormObj.packageSpecId);
    },
    async getDetail(id) {
      let res = await getDetail({ id });
      if (res.data.code != 200) return;
      this.detailData = res.data.data;
      this.detailData.assetsType = this.convertAssetsType(
        res.data.data.assetsType
      );
      this.isShowDetailPopup = true;
    },
    async getEnmu() {
      const { ["PC-PACKAGE-TYPE"]: packageType } = await this.$fetchEnumData([
        enumData.packageType,
      ]);
      let packageTypePopup = this.$findByProperty(
        this.popupDetailList,
        "id",
        "packageType"
      );
      this.$set(packageTypePopup, "list", packageType);
    },
    loadFun(tree, treeNode, resolve) {
      console.log(tree, treeNode, resolve, "tree, treeNode, resolve");
      getDetailList({
        parentId: tree.id,
        current: 1,
        size: 10,
        packageSpecId: tree.packageSpecId,
      }).then((res) => {
        console.log(res.data.data.records);
        this.$validateData(res.data.data.records);
        res.data.data.records.map((item) => {
          item.newNumUnit = `${item.unitCode}(${item.unitName})`;
        });
        resolve(res.data.data.records);
      });
    },

    getList() {
      getList(this.searchParams).then((res) => {
        if (res.data.code != 200) return;
        let data = res.data.data;
        this.$validateData(data);
        this.assTableData = data.records;
        this.totalNum = data.total;
      });
    },
    //获取明细分页
    async getDetailList(id) {
      const { data } = await getDetailList({
        size: 30,
        current: 1,
        packageSpecId: id,
        parentId: 0,
      });
      if (data.code != 200) return;
      console.log(data);
      this.$validateData(data.data);
      this.detailTableData = data.data.records;
      this.detailTableData.forEach((item) => {
        item.newNumUnit = `${item.unitCode}(${item.unitName})`;
      });
      console.log(this.detailTableData, data.data.records);
      this.currentDetailType = "detail";
    },
    //获取关联分页
    async getAssociationList(id) {
      const { data } = await getAssociationList({
        size: 30,
        current: 1,
        packageSpecId: id,
      });
      if (data.code != 200) return;
      this.$validateData(data.data);
      this.associationTableData = data.data.records;
      this.currentDetailType = "association";
    },
  },
  mounted() {
    // this.getList();
    this.getEnmu();
  },
  computed: {
    checkTitle() {
      return this.currentHandle == "add"
        ? "新增"
        : this.currentHandle == "rowEdit"
        ? "编辑"
        : "-";
    },
    ids() {
      let ids = [];
      this.$refs.trTable.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
    associationIds() {
      let ids = [];
      this.$refs.associationTable.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
    checkDetailTitle() {
      return this.currentDetailType == "detail"
        ? "包装规则明细"
        : this.currentDetailType == "association"
        ? "关联物料"
        : "-";
    },
  },
};
</script>

<style></style>
